<?php
/**
 * Created by PhpStorm.
 * User: fengzi
 * Date: 2019/5/29
 * Time: 14:32
 */

namespace app\vehicle\logic;
use app\vehicle\model\User;
use app\vehicle\model\WeixinAccessToken;
class tokenLogic{
    private static $appid = 'wx0ddf18de26ea6f90';
    private static $secret = '9e85e33eaff1c91418f8f8506bdaaba5';
    private static $grant_type = 'authorization_code';
    private static $url = 'https://api.weixin.qq.com/sns/jscode2session';

    public function getAccessToken(){
        $token = WeixinAccessToken::order('id desc')->find();
        if($token['stop_time']>time()-300){
            return $token['access_token'];
        }else {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . self::$appid . "&secret=" . self::$secret;
            $arr = json_decode(self::curlGet($url), true);
            if ($arr['access_token']) {
                $data['access_token'] = $arr['access_token'];
                $data['stop_time'] = time();
                WeixinAccessToken::insert($data);
                return $arr['access_token'];
            } else {
                return $arr;
            }
        }
    }
    /**
     * 根据用户传递 code 去微信服务器换取 openid
     */
    public function getOpenid($data) {
        if(!$data['encryptedData'] or !$data['iv']){
            return ['status' => -1, 'msg' => '请输入正确的参数'];
        }
        $result = self::decryptData($data['encryptedData'], $data['iv'],$data['session_key']);
        if (!is_array($result)) {
            return ['status' => -1,'code'=>$result, 'msg' => '加密数据不匹配'];
        }
        //return ['status' => -1,'code'=>$result, 'msg' => '加密数据不匹配'];
        $check = User::where('open_id','eq',$result['open_id'])->count();
        if(!$check) {
            $result['create_time'] = time();
            $result['uid'] = $result['unionId'];
            $user = User::create($result);
            $result['id'] = $user->id;
        }else{
            $result = User::where('open_id','eq',$result['open_id'])->find();
        }
        return ['status' => 1, 'msg' => '成功', 'result' => $result];
    }
    public function setToken($code){
        $new_url = self::$url . "?appid=".self::$appid."&secret=".self::$secret."&js_code={$code}&grant_type=".self::$grant_type;
        return self::curlGet($new_url);
    }
    /**
     * 颁发令牌 并将用户信息序列化成json，已token为键保存在本地缓存
     * 作用是 当用户不存在时创建用户   存在时返回用户 id
     */
    public function decryptData($encryptedData, $iv, $sessionKey) {
        $OK = 0;
        $IllegalAesKey = -41001;
        $IllegalIv = -41002;
        $IllegalBuffer = -41003;
        $DecodeBase64Error = -41004;
        if (strlen($sessionKey) != 24) {
            return $IllegalAesKey;
        }
        $aesKey=base64_decode($sessionKey);
        if (strlen($iv) != 24) {
            return $IllegalIv;
        }
        $aesIV=base64_decode($iv);
        $aesCipher=base64_decode($encryptedData);
        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj=json_decode( $result );
        if( $dataObj == NULL ) {
            return $IllegalBuffer;
        }
        if( $dataObj->watermark->appid != self::$appid ) {
            return $DecodeBase64Error;
        }
        $data = json_decode($result,true);
        $data['open_id'] = $data['openId'];
        unset($data['openId']);
        $data['nick_name'] = $data['nickName'];
        unset($data['nickName']);
        $data['head_pic'] = $data['avatarUrl'];
        unset($data['avatarUrl']);
        return $data;
    }
    private function curlGet($url, &$httpCode = 0)
    {
        //1、初始化curl
        $curl = curl_init();

        //2、告诉curl,请求的地址
        curl_setopt($curl, CURLOPT_URL, $url);
        //3、将请求的数据返回，而不是直接输出
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);

        $fileContents = curl_exec($curl); // 执行操作
        curl_close($curl); // 关键CURL会话

        return $fileContents; // 返回数据
    }
    /**
     * curl post
     * @param string $url
     * @param string $postData
     * @param array $options
     * @return mixed
     */
    public static function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}